package org.easySpace.common.handler;

import org.easySpace.common.enums.ErrorEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author lzh@aginome.com
 * @description 封装返回参数
 * @date 2022-06-02 17:33
 */

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ResponseDto {

    /**
     * 状态
     */
    @ApiModelProperty(value = "请求状态编号")
    private Integer code;
    /**
     * 给用户看的信息
     */
    @ApiModelProperty(value = "给用户看的信息")
    private String result;
    /**
     * 提示信息
     */
    @ApiModelProperty(value = "提示信息")
    private String message;
    /**
     * 数据
     */
    @ApiModelProperty(value = "数据")
    private Object data;

    /**
     * 自定义返回错误的提示
     *
     * @param errorEnum 异常枚举
     * @return
     */
    public static ResponseDto otherError(ErrorEnum errorEnum) {
        ResponseDto result = new ResponseDto();
        result.setResult("error");
        result.setMessage(errorEnum.getErrorMsg());
        result.setCode(errorEnum.getErrorCode());
        result.setData(null);
        return result;
    }

    /**
     * 打印异常信息
     *
     * @param errorEnum 异常枚举
     * @param e         异常
     * @return
     */
    public static ResponseDto errorMessage(ErrorEnum errorEnum, Exception e) {
        ResponseDto result = new ResponseDto();
        result.setResult("error");
        result.setCode(errorEnum.getErrorCode());
        result.setData(null);
        result.setMessage(e.getMessage());
        return result;
    }

    public static ResponseDto ok() {
        return new ResponseDto(200, "success", "success", (Object) null);
    }

    public static ResponseDto ok(String msg) {
        return new ResponseDto(200, "success", msg, (Object) null);
    }

    public static ResponseDto code(int code) {
        return new ResponseDto(code, "success", (String) null, (Object) null);
    }

    public static ResponseDto data(Object data) {
        return new ResponseDto(200, "success", "success", data);
    }

    public static ResponseDto error() {
        return new ResponseDto(500, "error", "error", (Object) null);
    }

    public static ResponseDto error(String msg) {
        return new ResponseDto(500, "error", msg, (Object) null);
    }

    public static ResponseDto get(int code, String msg, Object data) {
        return new ResponseDto(code, "success", msg, data);
    }

    public String toString() {
        return "{\"code\": " + this.getCode() + ", \"msg\": " + this.transValue(this.getMessage()) + ", \"data\": " + this.transValue(this.getData()) + "}";
    }

    private String transValue(Object value) {
        return value instanceof String ? "\"" + value + "\"" : String.valueOf(value);
    }

}
